package com.sicpa.common.utils;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * ExcelTemplateExportUtils Excel 模板导出工具类
 *
 * @author lwf
 */
public class ExcelTemplateExportUtils {

    /**
     * Excel 模板导出工具类
     * @param mapList
     * @param response
     * @param excelName
     * @throws IOException
     */
    public static void baseExportWorkbook(List<LinkedHashMap<String, Object>> mapList, HttpServletResponse response, String excelName, String excelFilePath) throws IOException, InvalidFormatException {
//        Resource resource = new ClassPathResource(excelFilePath);
//        Workbook workbook = new XSSFWorkbook(resource.getInputStream());
        Workbook workbook = new XSSFWorkbook(new FileInputStream(ResourceUtils.getFile(excelFilePath)));
        Sheet sheet = workbook.getSheetAt(0);
        for (int i = 0; i < mapList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Map<String, Object> tem = mapList.get(i);
            Collection<Object> objects = tem.values();
            List<Object> objectArrayList = new ArrayList<>(objects);
            for (int j = 0; j < objectArrayList.size(); j++) {
                Object tempV = objectArrayList.get(j);
                Cell cell = row.createCell(j);
                cell.setCellType(CellType.STRING);
                if (tempV != null) {
                    String temVs = tempV.toString();
                    if (temVs.length() > 100) {
                        cell.setCellValue(temVs.substring(0, 100));
                    } else {
                        cell.setCellValue(temVs);
                    }
                } else {
                    cell.setCellValue("");
                }
            }
        }
        response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "utf-8"));
        workbook.write(response.getOutputStream());
    }

}
